<?php

declare(strict_types=1);

namespace app\service\user\login;

use app\model\UserAuth;
use app\service\user\SmsCodeService;

class PhoneCode implements LoginInterface
{
    public function __construct(private readonly SmsCodeService $smsCodeService)
    {
    }

    public function login(array $credentials): array
    {
        $phone = $credentials['phone'] ?? '';
        $code = $credentials['code'] ?? '';

        // 这里假设有一个函数 verifySmsCode 用于验证短信验证码
        if (!$this->verifySmsCode($phone, $code)) {
            return [
                'status' => 'error',
                'msg' => '短信验证码错误'
            ];
        }

        $userAuth = UserAuth::where('identity_type', UserAuth::TYPE_SMS)
            ->where('identifier', $phone)
            ->find();

        if (!$userAuth) {
            return [
                'status' => 'error',
                'msg' => '用户不存在'
            ];
        }

        $userAuth->user()->update(['last_login_time' => date('Y-m-d H:i:s')]);
        return [
            'status' => 'success',
            'msg' => '登录成功',
            'user' => $userAuth->user
        ];
    }

    public function getIdentifier(): string
    {
        return 'phone_code';
    }

    private function verifySmsCode(string $phone, string $code): bool
    {
        return $this->smsCodeService->verifyCode(SmsCodeService::SCENE_LOGIN, $phone, $code);
    }
}
